<template>
    <div class="table">
        <div class="container">
            <div style="margin-bottom: 15px;margin-top: 15px;">
                <el-button type="primary" @click="addPolicy">新增</el-button>
                <el-button type="success" @click="editPolicy">修改</el-button>
<!--                <el-button type="danger" @click="delPolicy">删除</el-button>-->
            </div>
            <el-table
                    :data="tableList"
                    border stripe
                    style="width: 100%"
                    @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="strategyName" align="center" label="策略名称"></el-table-column>
                <el-table-column prop="strategyStartTime" :formatter="formatDateAll" align="center" label="执行日期"></el-table-column>
<!--                <el-table-column prop="time" align="center" label="执行时间"></el-table-column>-->
<!--                <el-table-column prop="fun" align="center" label="执行动作"></el-table-column>-->
<!--                <el-table-column prop="control" align="center" label="光温控制"></el-table-column>-->
                <el-table-column prop="strategyAction" :formatter="formatDes" align="center" label="策略描述"></el-table-column>
            </el-table>
        </div>
        <el-dialog title="策略编辑" :visible.sync="dialogIsShow" width="70%" v-dialogDrag>
            <div style="">
                <el-form ref="form" :model="form" label-width="80px">
                    <el-form-item label="策略名称">
                        <el-input v-model="form.name" style="width: 26%;"  placeholder="输入名称"></el-input>
                    </el-form-item>
                    <el-form-item label="有效日期">
                        <el-date-picker
                                v-model="form.startTime"
                                type="date"
                                :picker-options = {disabledDate:disabledDate}
                                value-format = "yyyy-MM-dd"
                                placeholder="选择开始日期">
                        </el-date-picker>
                        <span>--</span>
                        <el-date-picker
                                v-model="form.endTime"
                                type="date"
                                @change="endDate"
                                value-format = "yyyy-MM-dd"
                                placeholder="选择结束日期">
                        </el-date-picker>

                    </el-form-item>
<!--                    <el-form-item label="循环方式">-->
<!--                        <el-radio-group v-model="form.resource" @change="radioChange">-->
<!--                            <el-radio v-for="item in radioGroup" :label="item" :key="item"></el-radio>-->
<!--                        </el-radio-group>-->
<!--                        <el-checkbox-group v-model="form.type" v-if="form.resource == radioGroup[1]">-->
<!--                            <el-checkbox v-for="item in checkWeek" :label="item" :key="item" name="type"></el-checkbox>-->
<!--                        </el-checkbox-group>-->
<!--                    </el-form-item>-->

                    <el-form-item style="margin-bottom: 0;color: #f00;">
                        <span style="font-size: 12px;">请组合好您需要编辑的时间点，前四个时间点为主时间点其它为扩展时间点</span>
                    </el-form-item>
                    <el-form-item label="控制开关">
                        <div v-for="(item ,index) in controlList" style="margin-bottom: 10px;">
                            <el-select v-model="item.jobDate" placeholder="请选择日期" @change="selecJobDate(index)">
                                <el-option v-for="($item,$index) in tableData" :label="$item.label" :value="$item.value" :key="$item.value" :disabled="item.cronExpresstion == 0 && $index>0">
                                    <el-date-picker v-if="$index==tableData.length-1" @change="customDate(index)"
                                            v-model="value4"
                                            type="date"
                                                    :disabled="item.cronExpresstion == 0"
                                                    value-format = "yyyy-MM-dd"
                                            :placeholder="$item.label">
                                    </el-date-picker>
                                </el-option>
                            </el-select>
                            <span>-</span>
                            <el-time-picker
                                    v-model="item.jobTime"
                                    value-format="HH:mm:ss"
                                    placeholder="请选择时间">
                            </el-time-picker>
                            <span>-</span>
                            <el-select v-model="item.jobAction" placeholder="请选择动作">
                                <el-option v-for="item in actionList" :label="item.name" :value="item.value" :key="item.value"></el-option>
                            </el-select>
                            <el-button v-if="index<1" type="primary" icon="el-icon-plus" circle style="margin-left: 20px;" @click="addContrl"></el-button>
                            <el-button v-if="index>=1" type="danger" icon="el-icon-minus" circle style="margin-left: 20px;" @click="delContrl(index)"></el-button>
                        </div>

                    </el-form-item>
                </el-form>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogIsShow = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {getCategory,addStrategy,getTimerStrategy,updateTimerStrategy,deleteStrategyAction} from '../../../api/index';
    import {famatDatesTimes} from '../../common/com'
    export default {
        name: "timingStrategyManagement",
        data(){
            return {
                dialogIsShow:false,
                tableList:[],
                tableData:[
                    {label:'每天',value:'0'}, {label:'星期一',value:'1'}, {label:'星期二',value:'2'},
                    {label:'星期三',value:'3'}, {label:'星期四',value:'4'}, {label:'星期五',value:'5'},
                    {label:'星期六',value:'6'}, {label:'星期天',value:'7'}, {label:'指定日期',value:'99'},
                ],
                form: {
                    name: '',
                    startTime:'',
                    endTime:''
                },
                actionList:[],
                value4:'',
                controlList:[{jobType:'',jobTime:'',jobAction:'',jobDate:'',weekDay:'',cronExpresstion:'0'}],
                radioGroup:['每天','星期','指定日期'],
                checkWeek:['星期一','星期二','星期三','星期四','星期五','星期六','星期天'],
                multipleSelection:[],
                isEdit:false,
            }
        },
        created(){
            this.getAction();
            this.getDataList();
        },
        methods: {
            //小于当前日期的禁选
            disabledDate(val){
                if(val<new Date()){
                    return true;
                }
                return false;
            },
            //选择结束时间不能小于开始时间
            endDate(val){
                if(this.form.startTime>val){
                    this.$message.error('选择结束时间不能小于开始时间');
                    this.form.endTime = '';
                    return;
                }
            },
            //获取策略列表
            getDataList(){
                getTimerStrategy({}).then((res)=>{
                    console.log(res);
                    this.tableList = res.datas;
                })
            },
            //获取设备动作列表
            getAction(){
                getCategory({
                    "dicName":"设备动作"
                }).then((res) =>{
                    console.log(res)
                    this.actionList = res.expandData
                })
            },
            //控制操作选择时间判断当前选择的是每天，星期还是指定日期
            selecJobDate(val){
                // console.log(this.controlList[val].jobDate)
                if(this.controlList[val].jobDate<1){
                    this.controlList[val]['jobType'] = '0';
                }else if(this.controlList[val].jobDate<=7){
                    this.controlList[val]['jobType'] = '1';
                    this.controlList[val]['weekDay'] =  this.controlList[val].jobDate;
                }else{
                    this.controlList[val]['jobType'] = '2';
                }
                this.$forceUpdate();
            },
            //新增策略
            addPolicy(){
                this.dialogIsShow = true;
                this.isEdit = false;
                this.form = {
                    name: '',
                    startTime:famatDatesTimes(new Date().getTime(),'Y'),
                    endTime:''
                };
                this.controlList = [{jobType:'',jobTime:'',jobAction:'',jobDate:'',weekDay:'',cronExpresstion:'0'}];
            },
            //新增策略的动作操作
            addContrl(){
                if(this.controlList.length>14){
                    this.$message.error('最多可设置十五个时间段！')
                    return;
                }
                if(this.controlList.length>3){
                    var c=0;
                    for(var i=0;i<this.controlList.length;i++){
                        if(this.controlList[i].cronExpresstion==0){
                            c++;
                        }
                    }
                    if(c<4){
                        this.controlList.push({jobType:'',jobTime:'',jobAction:'',jobDate:'',weekDay:'',cronExpresstion:'0'})
                    }else{
                        this.controlList.push({jobType:'',jobTime:'',jobAction:'',jobDate:'',weekDay:'',cronExpresstion:'1'})
                    }
                }else{
                    this.controlList.push({jobType:'',jobTime:'',jobAction:'',jobDate:'',weekDay:'',cronExpresstion:'0'})
                }

                console.log(this.controlList)
            },
            //删除策略动作操作
            delContrl(index){
                if(this.controlList[index].actionId){
                    deleteStrategyAction({id:this.controlList[index].actionId}).then((res)=>{
                        if(res.success){
                            this.$message.success(res.message);
                            this.controlList.splice(index,1);
                            this.multipleSelection[0].strategyAction.splice(index,1)
                        }else{
                            this.$message.error(res.message);
                        }
                    })
                }else{
                    this.controlList.splice(index,1);
                }
                console.log(this.controlList)
            },
            //单选框
            radioChange(val){
                console.log(val);
            },
            //修改编辑策略
            editPolicy(){
                if(this.multipleSelection.length<=0){
                    this.$message.error('请选择需要修改的策略');
                    return ;
                }
                if(this.multipleSelection.length>1){
                    this.$message.error('每次只能选择一个策略修改');
                    return ;
                }

                this.form = {
                    name: this.multipleSelection[0].strategyName,
                    startTime:this.multipleSelection[0].strategyStartTime,
                    endTime:this.multipleSelection[0].strategyEndTime,
                };

                this.controlList = this.multipleSelection[0].strategyAction.map((val)=>{
                    var valStr = val;
                    if(val.jobType==1){
                        valStr.jobDate = val.weekDay;
                        // valStr.weekDay = '';
                    }else if(val.jobType==2){
                        valStr.weekDay = '';
                        valStr.jobDate = val.jobDate;
                    }else{
                        valStr.jobDate = '0';
                        valStr.weekDay = '';
                    }
                    return valStr;
                })
                if(this.controlList.length<=0){
                    this.controlList = [{jobType:'',jobTime:'',jobAction:'',jobDate:'',weekDay:''}]
                }
                this.dialogIsShow = true;
                this.isEdit = true;
                console.log(this.multipleSelection)
            },
            delPolicy(){
                if(this.multipleSelection.length<=0){
                    this.$message.error('请选择需要删除的策略');
                    return ;
                }
                if(this.multipleSelection.length>1){
                    this.$message.error('每次只能选择一个策略删除');
                    return ;
                }
            },
            //保存新增或者修改后的信息
            saveEdit(){
                if(!this.form.name){
                    this.$message.error('请输入名称');
                    return;
                }
                if(!this.form.endTime){
                    this.$message.error('请选择有效期的结束时间');
                    return;
                }
                for(var i=0;i<this.controlList.length;i++){
                    if(this.controlList[i].jobType==2 && this.controlList[i].jobDate == '99'){
                        this.$message.error('请选择指定日期的具体日期');
                        return;
                    }
                }
                this.controlList.sort(function(a,b){
                    var val1 =a.cronExpresstion;
                    var val2 =b.cronExpresstion;

                    if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
                        val1 = Number(val1);
                        val2 = Number(val2);
                    }

                    if (val1 < val2) {
                        return -1;
                    } else if (val1 > val2) {
                        return 1;
                    } else {
                        return 0;
                    }
                });
                console.log(JSON.stringify(this.controlList))
                if(this.isEdit){
                    var eidtObj = {
                        strategyStartTime:this.form.startTime,
                        strategyEndTime:this.form.endTime,
                        strategyName:this.form.name,
                        id:this.multipleSelection[0].id,
                        strategyAction:this.controlList.map((val,index)=>{
                            var valStr = val;
                            // if(this.multipleSelection[0].strategyAction&&this.multipleSelection[0].strategyAction[index]){
                            //     valStr['actionId'] = this.multipleSelection[0].strategyAction[index].actionId;
                            //     valStr['strategyId'] = this.multipleSelection[0].strategyAction[index].strategyId;
                            // }
                            if(val.jobType==1){
                                valStr.weekDay = val.jobDate;
                                valStr.jobDate = '';
                            }else if(val.jobType==2){
                                valStr.weekDay = '';
                                valStr.jobDate = val.jobDate;
                            }else{
                                valStr.jobDate = '';
                                valStr.weekDay = '';
                            }
                            return valStr;
                        })
                    }
                    // console.log(eidtObj);
                    // return;
                    updateTimerStrategy(eidtObj).then((res)=>{
                        if(res.success){
                            this.$message.success(res.message);
                            this.dialogIsShow = false;
                            this.getDataList();
                        }else{
                            this.$message.error(res.message);
                        }
                    })
                    return;
                }
                var obj = {
                    strategyStartTime:this.form.startTime,
                    strategyEndTime:this.form.endTime,
                    strategyName:this.form.name,
                    strategyAction:this.controlList.map((val)=>{
                        var valStr = val;
                        if(val.jobType==1){
                            valStr.weekDay = val.jobDate;
                            valStr.jobDate = '';
                        }else if(val.jobType==2){
                            valStr.weekDay = '';
                            valStr.jobDate = val.jobDate;
                        }else{
                            valStr.jobDate = '';
                            valStr.weekDay = '';
                        }
                        return valStr;
                    })
                };
                // console.log(obj);
                // return;
                addStrategy(obj).then((res)=>{
                    if(res.success){
                        this.$message.success(res.message);
                        this.dialogIsShow = false;
                        this.getDataList();
                    }else{
                        this.$message.error(res.message);
                    }
                })
            },
            //表格选中
            handleSelectionChange(val){
                this.multipleSelection = val;
                console.log(this.multipleSelection)
            },
            //自定义指定日期
            customDate(val){
                console.log(val)
                console.log(this.value4)
                this.controlList[val].jobDate =  this.value4;
                this.$forceUpdate();
            },
            //格式化返回的有效时间
            formatDateAll(row,cellVal){
                return row.strategyStartTime + '-' + row.strategyEndTime;
            },
            //格式化策略描述信息
            formatDes(row, column, cellValue){
               var str = ''
                if(!row.strategyAction||row.strategyAction.length<=0){
                    return ;
                }
                for(var i=0;i<row.strategyAction.length;i++){
                    if(row.strategyAction[i].jobType == 1){
                        str += this.checkWeek[row.strategyAction[i].weekDay - 1] + ' '+row.strategyAction[i].jobTime +' '+ this.arrFind(row.strategyAction[i].jobAction) + '；'  ;
                    }else if(row.strategyAction[i].jobType == 2){
                        str +=  row.strategyAction[i].jobDate + ' '+ row.strategyAction[i].jobTime +' '+ this.arrFind(row.strategyAction[i].jobAction) + '；'   ;
                    }else{
                        str += '每天' + ' '+ row.strategyAction[i].jobTime +' '+ this.arrFind(row.strategyAction[i].jobAction) + '；'   ;
                    }
                }
                return str;
            },
            //数组查找
            arrFind(val){
                var curr =  this.actionList.find((currentValue)=>{
                    return  currentValue.value == val;
                })
               return curr?curr.name:''
            },
        }
    }
</script>

<style scoped>

</style>
